package com.google.code.ratingscalculator;

import org.apache.log4j.Logger;

import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.*;

public class RatingsList {
    private static final Logger LOGGER = Logger.getLogger(RatingsList.class);

    private static final Pattern RATING_RECORD = Pattern.compile("^(.+?)\\s+([\\d.]+)"); 

    private List<Player> players = new ArrayList<Player>();

    private RatingsList() {}

    public static RatingsList createFromFile(File ratingsFile) throws IOException {
        RatingsList ratingsList = new RatingsList();
        LOGGER.trace("Creatign Ratings List from file");
        BufferedReader fileReader = new BufferedReader(new FileReader(ratingsFile));
        String ratingRecord = null;
        while((ratingRecord = fileReader.readLine())!=null) {
            Matcher matcher = RATING_RECORD.matcher(ratingRecord);
            if(matcher.matches()) {
                Player player = new Player();
                LOGGER.trace("Name:" + matcher.group(1));
                player.name = matcher.group(1);
                LOGGER.trace("Rating:" + matcher.group(2));
                player.rating = Double.parseDouble(matcher.group(2));
                ratingsList.players.add(player);
            } else {
                LOGGER.debug("Line ["+ratingRecord+"] doesnt matches the pattern " + RATING_RECORD.toString());
            }
        }
        Collections.sort(ratingsList.players, new PlayerRatingsComparator());
        return ratingsList;
    }

    public List<Player> getPlayers() {
        return players;
    }
}
